package cat.music.ut.ui.fragment

import android.app.Activity
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView.LayoutManager
import cat.music.ut.adapter.SearchResultAdapter
import cat.music.ut.base.BaseActivity
import cat.music.ut.base.BaseFragment
import cat.music.ut.bean.SearchResult
import cat.music.ut.comm.ext.setEmptyView
import cat.music.ut.component.click
import cat.music.ut.component.hide
import cat.music.ut.component.show
import cat.music.ut.databinding.FragmentIndexBinding
import cat.music.ut.databinding.FragmentSearchBinding
import cat.music.ut.ui.activity.MusicActivity
import cat.music.ut.ui.activity.WelcomeADActivity
import cat.music.ut.ui.dialog.DownloadDialogFragment
import cat.music.ut.viewmodel.SearchViewModel
import android.content.Intent
import android.net.Uri
import android.content.Context
import androidx.core.net.toUri

fun openLinkInBrowser(context: Context, url: String) {
    try {
        val uri = url.toUri()
        val intent = Intent(Intent.ACTION_VIEW, uri)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        context.startActivity(intent)
    } catch (e: Exception) {
        e.printStackTrace()
        // 可以提示用户链接无效或没有浏览器可用
    }
}
class SearchFragment : BaseFragment<FragmentSearchBinding>(),SearchResultAdapter.Listener {
    private val data = mutableListOf<SearchResult>()
    private val mSearchViewModel by lazy { ViewModelProvider(this)[SearchViewModel::class.java] }
    private val mSearchResultAdapter by lazy { SearchResultAdapter( requireActivity(),data) }
    private val mActivity by lazy { requireActivity() as MusicActivity }
    override fun getViewBinding(): FragmentSearchBinding {
        return FragmentSearchBinding.inflate(layoutInflater)
    }
    private var page = 0 // 当前索引
    override fun initView() {
        vb.tvSearch.click {
            hideSoftKeyboard(requireActivity(), mutableListOf(vb.searchInput))
            val text = vb.searchInput.text.toString()
            if (text == "关闭推广" || text == "关闭广告"){
                sp.ad = true
                toast("推广已关闭")
                return@click
            }
            if (!sp.ad && sp.searchCount % 5 == 0){
                sp.searchCount++
                startActivity(Intent(requireActivity(),WelcomeADActivity::class.java))
                return@click
            }
            sp.searchCount++
            if(text.isEmpty()){
                toast("输入音乐名")
                return@click
            }
            data.clear()
            mSearchResultAdapter.notifyDataSetChanged()
            showLoading()
            page = 0
            mSearchViewModel.search(text,page)
        }
        vb.rvResult.layoutManager = LinearLayoutManager(requireActivity())
        vb.rvResult.adapter = mSearchResultAdapter
        vb.rvResult.setEmptyView()
        vb.tvMore.hide()
    }

    override fun observe() {
        mSearchViewModel.mldSearchResult.observe(viewLifecycleOwner){
            val state = data.isNotEmpty() // 说明是加载更多
            val len = data.size // 说明是加载更多
            data.addAll(it)
            withUI {
                vb.tvMore.show(data.isNotEmpty())
                hideLoading()
                mSearchResultAdapter.notifyDataSetChanged()
                if (state){
                    vb.rvResult.scrollToPosition(len)
                }
            }
        }
        vb.searchInput.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE ||
                (event != null && event.keyCode == KeyEvent.KEYCODE_ENTER && event.action == KeyEvent.ACTION_DOWN)
            ) {
                // 回车按下后的逻辑
                vb.tvSearch.callOnClick()
                true  // 表示事件已消费
            } else {
                false
            }
        }
    }

    override fun initData() {

    }

    override fun initClick() {
        mSearchResultAdapter.listener = this
        vb.ivClose.click {
            vb.searchInput.setText("")
        }
        vb.tvMore.click {
            val text = vb.searchInput.text.toString()
            if(text.isEmpty()){
                toast("输入音乐名")
                return@click
            }
            showLoading()
            page ++
            mSearchViewModel.search(text,page)
        }
    }

    override fun clickItem(data: SearchResult) {
        showDownloadDialog(data)
    }
    private fun showDownloadDialog(data: SearchResult){
        DownloadDialogFragment.create(data).show(requireActivity() as BaseActivity<*>)
    }
}
fun hideSoftKeyboard(context: Context, viewList: List<View>?) {
    if (viewList == null) return

    val inputMethodManager =
        context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager

    for (v in viewList) {
        inputMethodManager.hideSoftInputFromWindow(
            v.windowToken,
            InputMethodManager.HIDE_NOT_ALWAYS
        )
    }
}